<?php

class BuyrecordsController extends \BaseController {

	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index()
	{
		//
        $PATH = "http://aebo.qiniudn.com/";
        $customer_id = Session::get('customer_id');
        $type = Input::get('type');
        if($type == 'final'){
            $buyrecords = Buyrecord::where('customer_id',$customer_id)
                ->where('state','>',0)
                ->orderBy('created_at', 'DESC')
                ->get();
        }elseif($type == 'will'){
            $buyrecords = Buyrecord::where('customer_id',$customer_id)
                ->where('state',0)
                ->orderBy('created_at', 'DESC')
                ->get();
        }else{
            $buyrecords = Buyrecord::where('customer_id',$customer_id)
                ->orderBy('created_at', 'DESC')
                ->get();
        }
        return View::make('buyrecords.index',compact('buyrecords','PATH','type'));
	}



	/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create()
	{
		//

	}


	/**
	 * Store a newly created resource in storage.
	 *
	 * @return Response
	 */
	public function store()
	{
		//
	}


	/**
	 * Display the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{

        $customer_id = Session::get('customer_id');
        $customer = Customer::find($customer_id);

        $buyrecord = Buyrecord::find($id);
        $commodity = Commodity::find($buyrecord->commodity_id);
        if($buyrecord->state > 0){
            $user = User::where('city',$customer->city)->where('permissions','{"city":1}')->first();
            return View::make('buyrecords.success',compact('buyrecord','user'));
        }else{

            if($buyrecord->Commodity->member_points > $customer->all_points-$customer->use_points){
                $enable = 0;
            }else{
                $enable = 1;
            }

            $pub = Pub::find(1);
//        if (Cache::has('token'))
//        {
//            //
//            $value = Cache::get('token');
//        }else{
//            $value =  Wechat::get_access_token($pub->AppID,$pub->AppSecret);
//            Cache::put('token', $value, 240);
//        }

            $time = $buyrecord->out_trade_no;

            $appid = $pub->AppID;
            $appsecret = $pub->AppSecret;



        $total = $commodity->member_price*100;
//            $total = 1;
            $body = $buyrecord->Commodity->name;

//获取code
//        $code = isset($_GET['code'])?$_GET['code']:'no code';
////echo 'code: [',$code,']<br />';
//
////获取code后，请求以下链接获取access_token：
//        $acc = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$appsecret.'&code='.$code.'&grant_type=authorization_code';
//        $res = json_decode(https_request($acc),true);
//        $access_token = $res['access_token'];
            $openid = $customer->openid;
//echo $access_token , '<br />';
//echo $openid , '<br />';




            $xml = '<xml>
  <openid><![CDATA['.$openid.']]></openid>
  <body><![CDATA['.$body.']]></body>
  <out_trade_no><![CDATA['.$time.']]></out_trade_no>
  <total_fee>'.$total.'</total_fee>
  <notify_url><![CDATA[http://crm.leaderphos.com/pay/buy_notify/]]></notify_url>
  <trade_type><![CDATA[JSAPI]]></trade_type>
  <appid><![CDATA['.$appid.']]></appid>
  <mch_id>1226760102</mch_id>
  <spbill_create_ip><![CDATA['.$_SERVER['REMOTE_ADDR'].']]></spbill_create_ip>
  <nonce_str><![CDATA[60uf9sh6nmppr9azveb2bn7arhy79izk]]></nonce_str>
</xml>';
            $arr = $this->xmlToArray($xml); //转成数组
            $str = $this->formatBizQueryParaMap($arr,false); //字典序排序 1
            $stringSignTemp = $str.'&key='.$pub->apiKey;  //把key拼接上 2
            $md5 = md5($stringSignTemp); //md5 3
            $sign = strtoupper($md5); //再转大写 获取sign 4
//echo 'sign: ',$sign ,'<br />';



//提交xml到指定的url上
            $x = '<xml>
  <openid><![CDATA['.$openid.']]></openid>
  <body><![CDATA['.$body.']]></body>
  <out_trade_no><![CDATA['.$time.']]></out_trade_no>
  <total_fee>'.$total.'</total_fee>
  <notify_url><![CDATA[http://crm.leaderphos.com/pay/buy_notify/]]></notify_url>
  <trade_type><![CDATA[JSAPI]]></trade_type>
  <appid><![CDATA['.$appid.']]></appid>
  <mch_id>1226760102</mch_id>
  <spbill_create_ip><![CDATA['.$_SERVER['REMOTE_ADDR'].']]></spbill_create_ip>
  <nonce_str><![CDATA[60uf9sh6nmppr9azveb2bn7arhy79izk]]></nonce_str>
  <sign><![CDATA['.$sign.']]></sign>
</xml>';
            $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';  //把xml数据提交到这个url上
            $res = $this->xmlToArray($this->postXmlCurl($x,$url));  //返回结果为xml格式 再转成数组
            $prepay_id = ($res['prepay_id']); //得到了 prepay_id
//echo $prepay_id;



            $jsApiParameters = $this->getParameters($appid,$prepay_id,$pub->apiKey);

//        echo $jsApiParameters;

            return View::make('buyrecords.show',compact('jsApiParameters','buyrecord','commodity','time','enable'));
        }


	}


	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		//
	}


	/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{
		//
	}


	/**
	 * Remove the specified resource from storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function destroy($id)
	{
		//


	}





    /**
     *  作用：产生随机字符串，不长于32位
     */
    function createNoncestr( $length = 32 ){
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str ="";
        for ( $i = 0; $i < $length; $i++ )  {
            $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return $str;
    }
    /**
     *  作用：设置jsapi的参数
     */
    function getParameters($appid,$prepay_id,$apiKey)
    {
        $jsApiObj["appId"] = $appid;
        $timeStamp = time();
        $jsApiObj["timeStamp"] = "$timeStamp";
        $jsApiObj["nonceStr"] = $this->createNoncestr();
        $jsApiObj["package"] = "prepay_id=$prepay_id";
        $jsApiObj["signType"] = "MD5";

        //把上面的参数字典序排序
        $one = $this->formatBizQueryParaMap($jsApiObj,false);
        $two = $one.'&key='.$apiKey;
        $three = md5($two);
        $four= strtoupper($three);

        $jsApiObj["paySign"] = $four;
        $parameters = json_encode($jsApiObj);

        return $parameters;
    }

    //http 请求
    function https_request($url,$data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

    /**
     *  作用：以post方式提交xml到对应的接口url
     */
    function postXmlCurl($xml,$url,$second=30){
        //初始化curl
        $ch = curl_init();
        //设置超时
        //curl_setopt($ch, CURLOP_TIMEOUT, $second);
        //这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        //运行curl
        $data = curl_exec($ch);
        curl_close($ch);
        //返回结果
        if($data){
            //curl_close($ch);
            return $data;
        }else{
            $error = curl_errno($ch);
            echo "curl出错，错误码:$error"."<br>";
            echo "<a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>错误原因查询</a></br>";
            curl_close($ch);
            return false;
        }
    }


    /**
     *  作用：将xml转为array
     */
    function xmlToArray($xml){
        //将XML转为array
        $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $array_data;
    }


    /**
     *  作用：格式化参数，签名过程需要使用
     */
    function formatBizQueryParaMap($paraMap, $urlencode){
        $buff = "";
        ksort($paraMap);
        foreach ($paraMap as $k => $v){
            if($urlencode){
                $v = urlencode($v);
            }
            //$buff .= strtolower($k) . "=" . $v . "&";
            $buff .= $k . "=" . $v . "&";
        }
        $reqPar;
        if (strlen($buff) > 0) {
            $reqPar = substr($buff, 0, strlen($buff)-1);
        }
        return $reqPar;
    }

}
